package com.zhengshang.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.zhengshang.admin.security.service.TokenService;
import com.zhengshang.common.annotation.Log;
import com.zhengshang.common.config.ZhengshangConfig;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginUser;
import com.zhengshang.common.enums.BusinessType;
import com.zhengshang.common.oss.OssUtils;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.MessageUtils;
import com.zhengshang.common.utils.SecurityUtils;
import com.zhengshang.common.utils.ServletUtils;
import com.zhengshang.common.utils.file.FileUploadUtils;
import com.zhengshang.common.utils.uuid.IdUtils;
import com.zhengshang.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 个人信息 业务处理
 * 
 *
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "{user.profile.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        if (userService.updateUserProfile(user) > 0)
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("user.profile.edit.error"));
    }

    /**
     * 重置密码
     */
    @Log(title = "{user.profile.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error(MessageUtils.message("user.profile.edit.old.password"));
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error(MessageUtils.message("user.profile.edit.new.password"));
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("user.profile.edit.password.error"));
    }

    /**
     * 头像上传
     */
    @Log(title = "{user.avatar.log.title}", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//            String avatar = FileUploadUtils.upload(ZhengshangConfig.getAvatarPath(), file);
            JSONObject object = OssUtils.uploadFile(file, OssUtils.FILE_TYPE_AVATAR, IdUtils.simpleUUID() + ".jpg");
            if (object == null) {
                return AjaxResult.error("oss上传失败");
            }
            String avatar = object.getString("objectID");
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error(MessageUtils.message("user.avatar.upload.error"));
    }
}
